<?php
/**
 * 品牌加盟
 */

defined('InShopNC') or exit('Access Invalid!');

class brand_allianceControl extends MobileControl {
	public function __construct() {
		parent::__construct();
		//检查是否登录
		$this->isLogin();
	}
	
	//地图定位
	public function indexOp(){
		$brand_id = (int)$_REQUEST['brand_id'];
		if($brand_id <= 0){
			appMessage('参数错误','index.php?act=brand');
		}
		$sql = "SELECT * FROM #__brand_alliance_setting WHERE brand_id = '$brand_id'";
		$setting = Db::queryRow($sql);
		if(empty($setting) || !is_array($setting)){
			appMessage('该品牌暂不支持加盟','index.php?act=brand');
		}
                 $sql = "SELECT bc_id FROM #__brand WHERE brand_id = '$brand_id'";
                 $bc_id = Db::queryOne($sql);
                  
                  Tpl::output('bc_id',$bc_id);
		Tpl::output('setting',$setting);
		Tpl::showpage('brand_alliance');
	}

	//非地图定位
	public function index_putOp(){
		$brand_id = (int)$_REQUEST['brand_id'];
		if($brand_id <= 0){
			appMessage('参数错误','index.php?act=brand');
		}
		$sql = "SELECT * FROM #__brand_alliance_setting WHERE brand_id = '$brand_id'";
		$setting = Db::queryRow($sql);
		if(empty($setting) || !is_array($setting)){
			appMessage('该品牌暂不支持加盟','index.php?act=brand');
		}
                 $sql = "SELECT bc_id FROM #__brand WHERE brand_id = '$brand_id'";
                 $bc_id = Db::queryOne($sql);
                  
                  Tpl::output('bc_id',$bc_id);
		Tpl::output('setting',$setting);
		Tpl::showpage('brand_alliance_put');
	}
	
	//服务协议
	public function treatyOp(){
		$s_id = intval($_GET['s_id']);
		$sql = "SELECT * FROM #__brand_alliance_setting WHERE s_id = '$s_id' ";
		$setting = Db::queryRow($sql);
		Tpl::output('setting',$setting);
		Tpl::showpage('brand_treaty');
	}
	
	//加盟记录添加
	public function alliance_addOp(){
		$ref_url = trim($_REQUEST['ref_url']);
                $err_link = $ref_url ? $ref_url :  'index.php?act=brand_alliance&brand_id='.$_POST['brand_id'];
		
		if(intval($_POST['is_find'] == 1)){
			$_POST['province_id'] = $_POST['city_id'] = $_POST['area_id'] = 0;
			include BasePath.'/data/area/areaall.php';
			foreach($area_array as $k=>$v){
				if($v['area_name'] == $_POST['province']){
					$_POST['province_id'] = $k;
				}
				if($v['area_name'] == $_POST['city']){
					$_POST['city_id'] = $k;
				}
				if($v['area_name'] == $_POST['district']){
					$_POST['area_id'] = $k;
				}
			}
			$_POST['pca_info'] = trim($_POST['province']).trim($_POST['city']).trim($_POST['district']); 
		}
		$obj_validate = new Validate ();
		$obj_validate->validateparam = array (
				array ("input" => $_POST ["province_id"],"require" => "true","message" => '参数错误' ), 
				array ("input" => $_POST ["city_id"],"require" => "true","message" => '参数错误' ),
				array ("input" => $_POST ["area_id"],"require" => "true","message" => '参数错误' ),
				array ("input" => $_POST ["pca_info"],"require" => "true","message" => '参数错误' ),
				array ("input" => $_POST ["address"],"require" => "true","message" => '参数错误' ),
				array ("input" => $_POST ["lng"],"require" => "true","message" => '参数错误' ),
				array ("input" => $_POST ["lat"],"require" => "true","message" => '参数错误' ),
				array ("input" => $_POST ["brand_id"],"require" => "true","message" => '参数错误' ),
				array ("input" => $_POST ["brand_name"],"require" => "true","message" => '参数错误' ),
				array ("input" => $_POST ["true_name"],"require" => "true","message" => '参数错误' ),
				array ("input" => $_POST ["mobile"],"require" => "true","message" => '参数错误' ),
				array ("input" => $_POST ["store_name"],"require" => "true","message" => '参数错误' )
		);
		$error = $obj_validate->validate ();
		if ($error != '') {
			appJump('参数错误',$err_link);
		}
		if((int)$_POST['agreement'] <= 0){
			appJump('请同意该服务协议',$err_link);
		}
		$sql = "SELECT COUNT(*) FROM #__brand_alliance WHERE member_id = '{$_SESSION['member_id']}' AND brand_id = '{$_POST['brand_id']}'";
		if(Db::queryOne($sql) > 0){
			appJump('您已加盟过该品牌',$err_link);
		}
		
		$insert_array = array();
		$insert_array['member_id'] = (int)$_SESSION['member_id'];
		$insert_array['member_name'] = trim($_SESSION['member_name']);
		$insert_array['province_id'] = (int)$_POST['province_id'];
		$insert_array['city_id'] = (int)$_POST['city_id'];
		$insert_array['area_id'] = (int)$_POST['area_id'];
		$insert_array['pca_info'] = trim($_POST['pca_info']);
		$insert_array['address'] = trim($_POST['address']);
		$insert_array['brand_id'] = (int)$_POST['brand_id'];
		$insert_array['brand_name'] = trim($_POST['brand_name']);
		$insert_array['true_name'] = trim($_POST['true_name']);
		$insert_array['mobile'] = trim($_POST['mobile']);
		$insert_array['store_name'] = trim($_POST['store_name']);
		$insert_array['lng'] = floatval($_POST['lng']);
		$insert_array['lat'] = floatval($_POST['lat']);
		$insert_array['add_time'] = TIMESTAMP;

		if(Db::insert('brand_alliance',$insert_array)){
			appJump('恭喜您，加盟成功！即将转到支付页面。请您尽快支付加盟费用，否则自动取消加盟资格','index.php?act=brand_alliance&op=alliance_pay&brand_id='.$_POST['brand_id']);
		}else{
			appJump('加盟失败！',$err_link);
		}
	}

	//加盟--支付页面
	public function alliance_payOp(){
		$brand_id = (int)$_REQUEST['brand_id'];
		
		$sql = "SELECT * FROM #__gold_payment WHERE payment_state = '1'";
		$payment_list = Db::queryAll($sql);
		foreach ($payment_list as $k=>$v) {
			if(!in_array($v['payment_code'],array('alipaywap','chinapaywap'))){
				unset($payment_list[$k]);
			}
		}
				
		$sql = "SELECT * FROM #__brand_alliance_setting WHERE brand_id = '$brand_id'";
		$setting = Db::queryRow($sql);

		Tpl::output('setting',$setting);
		Tpl::output('payment_list',$payment_list);
		Tpl::showpage('brand_alliance_pay');
	}
	
	//加盟列表
	public function listOp(){
		$sql = "SELECT * FROM #__brand_alliance WHERE member_id = '{$_SESSION['member_id']}' ";
		$list = Db::queryAll($sql);
		
		Tpl::output('list',$list);
		Tpl::showpage('brand_alliance_list');
	}
	
	//充值--支付页面
	public function brand_payOp(){
		$brand_id = (int)$_REQUEST['brand_id'];
		
		$sql = "SELECT * FROM #__gold_payment WHERE payment_state = '1'";
		$payment_list = Db::queryAll($sql);
		foreach ($payment_list as $k=>$v) {
			if(!in_array($v['payment_code'],array('alipaywap','chinapaywap'))){
				unset($payment_list[$k]);
			}
		}

		$sql = "SELECT * FROM #__brand_alliance_setting WHERE brand_id = '$brand_id'";
		$setting = Db::queryRow($sql);
		$is_paid = Db::queryOne("SELECT is_paid FROM #__brand_alliance WHERE member_id = '{$_SESSION['member_id']}' AND brand_id = '$brand_id' ");
		
		Tpl::output('is_paid',$is_paid);
		Tpl::output('setting',$setting);
		Tpl::output('payment_list',$payment_list);
		Tpl::showpage('brand_pay');
	}
	
	//品牌金额日志
	public function brand_deposit_logOp(){
		$brand_id = (int)$_REQUEST['brand_id'];
		if($brand_id <= 0){
			appMessage('缺少参数');
		}
		
		$where = '';
		if (!empty($_GET ['stage'])) {
			$where .= " AND bdlog_stage = '{$_GET['stage']}' ";
		}
		if (!empty($_GET ['stime'])) {
			$where .= " AND bdlog_addtime > ".strtotime($_GET['stime']); 
		}
		if (!empty($_GET ['etime'])) {
			$where .= " AND bdlog_addtime < ". (strtotime($_GET['etime']) + 86400) ; 
		}
		if (!empty($_GET ['description'])) {
			$where .= " AND bdlog_desc LIKE '%{$_GET['description']}%'";
		}
		$sql = "SELECT * FROM #__brand_deposit_log WHERE bdlog_memberid = '{$_SESSION['member_id']}' AND bdlog_brandid = '$brand_id' AND bdlog_type IN(0,2) $where ORDER BY bdlog_id DESC";
		$pagesize=10;
		$curpage=$_GET['curpage'];
		$rs = db::PageQuery($sql,$curpage,$pagesize);
		$page = new Page();
		$page->setEachNum($pagesize);
		$page->setNowPage($curpage);
		$page->setTotalNum($rs->pageRows());		
		$list_log = $rs->fetchAll();
		
		$brand_name = Db::queryOne("SELECT brand_name FROM #__brand WHERE brand_id = '$brand_id' ");
		Tpl::output('brand_name',$brand_name);
		Tpl::output('show_page',$page->show());
		Tpl::output ( 'menu_sign', 'brand_alliance_list' );
		Tpl::output ( 'list_log', $list_log);
		Tpl::showpage('brand_deposit_log');
	}
	
	//获取品牌加盟记录
	public function get_pointsOp(){
		$brand_id = (int)$_GET['brand_id'];
		$lng = floatval($_GET['lng']);
		$lat = floatval($_GET['lat']);
		$distance = floatval($_GET['distance']); 
		$incre = $distance/(1*111*1000);
		//清除加盟大于10分钟未支付加盟费用的记录
                $time = TIMESTAMP - 600;
                $sql = "SELECT * FROM #__brand_alliance WHERE brand_id = '$brand_id' AND is_paid = 1 AND is_effective = 1 AND add_time < $time ";
                $del_res = Db::queryAll($sql);
                if(is_array($del_res)){
                    foreach($del_res as $v){
                        brand_allianceModel::sendNotic($v['brand_id'], $v['lng'], $v['lat']);
                    }
                }
		Db::delete('brand_alliance',"brand_id = '$brand_id' AND is_paid = 1 AND is_effective = 1 AND add_time < $time ");
		$sql = "SELECT store_name,pca_info,address,lng,lat FROM #__brand_alliance WHERE brand_id = '$brand_id' AND lat > $lat - $incre AND lat < $lat + $incre AND lng > $lng - $incre AND lng < $lng + $incre ORDER BY ACOS(SIN(($lat * PI()) / 180 ) * SIN((lat * PI()) / 180 ) + COS(($lat * PI()) / 180 ) * COS((lat * PI()) / 180 ) * COS(($lng * PI()) / 180 - (lng * PI()) / 180 ) ) * 6380 ASC";
		$list = Db::queryAll($sql);
		$res = array();
		if(!empty($list) && is_array($list)){
			 foreach ($list as $k=>$v){
				//如已使用保证金支付订单则加盟失效，剔除该记录
				if($v['is_paid'] == 2 && $v['is_effective'] == 1){
					unset($list[$k]);
				}
			 }
			 $res['state'] = true;
			 $res['list'] = $list;
                            //该区域内不能加盟的保存加盟提醒记录
                            if(intval($_SESSION['is_login'])){
                                $notic_arr = array();
                                $notic_arr['brand_id'] = $brand_id;
                                $notic_arr['brand_name'] = trim($_GET['brand_name']);
                                $notic_arr['member_id'] = intval($_SESSION['member_id']);
                                $notic_arr['member_name'] = trim($_SESSION['member_name']);
                                $notic_arr['member_mobile'] = preg_match('/^1[3|5|7|8]\d{9}$/', trim($_GET['mobile'])) ? trim($_GET['mobile']) : $_SESSION['member_mobile'];
                                $notic_arr['lng'] = $lng;
                                $notic_arr['lat'] = $lat;
                                $sql = "SELECT * FROM #__brand_alliance_notic WHERE brand_id = '$brand_id' AND member_id = '{$notic_arr['member_id']}' AND lng = '$lng' AND lat = '$lat'";
                                if(!Db::queryRow($sql)){
                                    Db::insert('brand_alliance_notic',$notic_arr);
                                }
                            }
		}else{
                           $sql = "SELECT COUNT(*) FROM #__ams_store WHERE lat > $lat - $incre AND lat < $lat + $incre AND lng > $lng - $incre AND lng < $lng + $incre ORDER BY ACOS(SIN(($lat * PI()) / 180 ) * SIN((lat * PI()) / 180 ) + COS(($lat * PI()) / 180 ) * COS((lat * PI()) / 180 ) * COS(($lng * PI()) / 180 - (lng * PI()) / 180 ) ) * 6380 ASC";
                          $num = Db::queryOne($sql);
			$res['state'] = false;
                          $res['num'] = $num;
		}
		exit(json_encode($res));
	}
	
}